package OrderService

import (
	"context"
	"database/sql"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"strings"
)

func getOrderInfoSteps(ctx context.Context, orderMap g.Map) g.Map {
	resultMap := g.Map{
		"1": g.Map{
			"title":       "下单",
			"icon":        "el-icon-edit",
			"description": gtime.New(orderMap["create_at"]).Format("Y-m-d H:i:s"),
		},
		/*"2": g.Map{
			"title":       "付款",
			"icon":        "el-icon-money",
			"description": "",
		},
		"3": g.Map{
			"title":       "备货",
			"icon":        "el-icon-sell",
			"description": "",
		},
		"4": g.Map{
			"title":       "发货",
			"icon":        "el-icon-truck",
			"description": "",
		},
		"5": g.Map{
			"title":       "完成",
			"icon":        "el-icon-s-claim",
			"description": "",
		},*/
	}

	typeIn := []string{
		"back_pay",
		"confirm_goods",
		"send_express",
		"confirm_order",
		"member_pay",
		"close_order",
	}
	var orderLogList []*entity.OrderLog
	err := toolsDb.GetUnSafaTable(ctx, "order_log").Where("order_id", orderMap["id"]).Where("type IN (?)", typeIn).Fields(
		"id,order_id,type,admin_id,member_id,create_at",
	).Order("id ASC").Structs(&orderLogList)
	if err != nil {
		return resultMap
	}

	typeToInt := g.MapStrStr{
		"back_pay":      "2",
		"member_pay":    "2",
		"confirm_goods": "3",
		"send_express":  "4",
		"confirm_order": "5",
		"close_order":   "6",
	}

	olTypeTitles := g.MapStrStr{
		"back_pay":      "后台付款",
		"member_pay":    "会员付款",
		"confirm_goods": "备货",
		"send_express":  "发货",
		"confirm_order": "完成",
		"close_order":   "关闭",
	}
	olTypeIcons := g.MapStrStr{
		"back_pay":      "el-icon-money",
		"member_pay":    "el-icon-money",
		"confirm_goods": "el-icon-sell",
		"send_express":  "el-icon-truck",
		"confirm_order": "el-icon-s-claim",
		"close_order":   "el-icon-remove",
	}

	for _, item := range orderLogList {
		switch item.Type {
		case "back_pay", "member_pay", "confirm_goods", "send_express", "confirm_order", "close_order":
			resultMap[typeToInt[item.Type]] = g.Map{
				"title":       olTypeTitles[item.Type],
				"icon":        olTypeIcons[item.Type],
				"description": gtime.New(item.CreateAt).Format("Y-m-d H:i:s"),
			}
			break
		}
	}
	status := gconv.Int(orderMap["status"])
	// 如果刚创建订单，删除 确认订单
	if status < 1 {
		delete(resultMap, "confirm_order")
	}
	// 如果订单完成，则删除 关闭订单
	if status == 99 {
		delete(resultMap, "close_order")
	}

	return resultMap
}

// 获取当前激活的步骤
func getNowStepActive(ctx context.Context, status int) int {
	fanhui := -1
	switch status {
	case 99:
		fanhui = 5
		break
	case 4, 3, 2, 1:
		fanhui = status
		break
	}

	return fanhui
}

func getAddressInfoByorderId(ctx context.Context, orderId string) g.Map {
	defaultMap := g.Map{
		"recipient_name":   "",
		"recipient_mobile": "",
		"province":         "",
		"city":             "",
		"area":             "",
		"street":           "", // 街道
		"address":          "",
		"zipcode":          "",
	}
	orderModel := getOrderModel(ctx, gconv.Int(orderId))
	if orderModel == nil {
		return defaultMap
	}
	one, err := toolsDb.GetUnSafaTable(ctx, "order_address").Where("order_id", orderId).One()
	if err != nil {
		return defaultMap
	}

	if one.IsEmpty() {
		return defaultMap
	}
	oneMap := one.Map()
	tmp := gjson.New(oneMap["address_json"]).Map()
	tmp["recipient_name"] = orderModel.RecipientName
	tmp["recipient_mobile"] = orderModel.RecipientMobile
	return tmp
}

func Info(ctx context.Context, req *BaseReq.I) *response.JsonResponse {
	obj := toolsDb.GetUnSafaTable(ctx, "order").As("o").LeftJoin(
		"member m", "m.id = o.member_id",
	).LeftJoin(
		"order_price op", "o.id = op.order_id",
	).LeftJoin(
		"store s", "o.store_id = s.id",
	).Fields(strings.Join(req.PageQueryOp.SelectFields, ",")).WherePri(
		"o.id",
		req.Id,
	)
	res, err := obj.One()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}

	orderId := gconv.Int(req.Id)
	subList := GetOrderSubAndExpressListByOrderIds(ctx, []int{orderId})
	if len(subList) < 1 {
		return response.FailByRequestMessage(nil, "子订单数据获取失败")
	}
	// 附加数据
	resMap := res.Map()
	resMap["pay_logs"] = getPayLogs(ctx, gconv.String(resMap["id"]))
	resMap["subs"] = subList[orderId]
	resMap["price_table"] = getOrderPriceTableByOrderModel(resMap)
	resMap["is_modfiy_price"] = getOrderIsModfiyPriceByOrderModel(resMap)
	if len(gconv.String(resMap["store_name"])) < 1 {
		resMap["store_name"] = "自营"
	}
	resMap["addresss"] = getAddressInfoByorderId(ctx, gconv.String(resMap["id"]))
	resMap["steps"] = getOrderInfoSteps(ctx, resMap)
	resMap["step_active"] = getNowStepActive(ctx, gconv.Int(resMap["status"]))

	return response.SuccessByRequestMessageData(nil, "获取成功",
		resMap)
}
